package net.projects.pro5_rss.reader;

import net.projects.pro5_rss.Buffer.NewsBuffer;
import net.projects.pro5_rss.writer.NewsWriterTask;
import org.apache.log4j.Logger;

import java.io.BufferedReader;
import java.io.FileReader;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class NewsSystem implements Runnable {
    private String sourcePath;
    private ScheduledThreadPoolExecutor executor;
    private NewsBuffer buffer;
    private final Logger log = Logger.getLogger(NewsSystem.class.getName());

    public NewsSystem(String sourcePath) {
        this.sourcePath = sourcePath;
        this.executor = new ScheduledThreadPoolExecutor(Runtime.getRuntime().availableProcessors());
        this.buffer = new NewsBuffer();
    }

    @Override
    public void run() {
        NewsWriterTask writerTask = new NewsWriterTask(buffer);
        Thread writerThread = new Thread(writerTask);
        writerThread.start();

        Path file = Paths.get(sourcePath); // Corrected to Paths.get()
        try (BufferedReader reader = new BufferedReader(new FileReader(file.toFile()))) {
            String line;
            while ((line = reader.readLine()) != null) {
                String[] strs = line.split(";");
                if (strs.length == 2) {
                    String rssName = strs[0];
                    String url = strs[1];

                    NewsProductTask productTask = new NewsProductTask(buffer, rssName, url);
                    this.executor.scheduleWithFixedDelay(productTask, 0, 1, TimeUnit.MINUTES);
                }
            }
        } catch (Exception e) {
            log.error("Error reading source file: " + e.getMessage());
        } finally {
            if (executor != null) {
                executor.shutdown(); // Shutdown executor when finished
            }
        }
    }
}
